<template>
  <div class="the-list">
    <div class="panel-search">
      <el-form inline :model="table.query" class="demo-form-inline">
        <el-form-item label="活动ID">
          <el-input
            v-model="table.query.eventsId"
            placeholder="活动ID"
            clearable
          />
        </el-form-item>
        <el-form-item label="活动名称">
          <el-input
            v-model="table.query.eventsName"
            placeholder="活动名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="上架状态">
          <el-select
            v-model="table.query.eventsStatus"
            placeholder="活动状态"
            style="width: 240px">
            <el-option label="全部" value="" />
            <el-option
              v-for="item in table.statusList"
              :key="item.name"
              :label="item.name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动发布人" v-if="!table.isMerchant">
          <el-input
            v-model="table.query.publisher"
            placeholder="活动发布人"
            clearable
          />
        </el-form-item>
        <el-form-item label="活动时间">
          <el-date-picker
            v-model="table.query.eventsStartTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="请选择时间"
            end-placeholder="请选择时间"
          />
        </el-form-item>
        <el-form-item label="报名时间">
          <el-date-picker
            v-model="table.query.signUpEndTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="请选择时间"
            end-placeholder="请选择时间"
          />
        </el-form-item>
        <el-form-item label="是否自营">
          <el-select
            v-model="table.query.selfSupport"
            placeholder="活动状态"
            style="width: 240px">
            <el-option label="全部" value="" />
            <el-option label="非自营" value="0"/> 
            <el-option label="自营" value="1"/> 
          </el-select>
        </el-form-item>
        <el-form-item label="进行状态">
          <el-select
            v-model="table.query.timeStatus"
            placeholder="进行状态"
            style="width: 200px">
            <el-option label="全部" value="" />
            <el-option
              v-for="item in table.activityList"
              :key="item.name"
              :label="item.name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="查看排序">
          <el-switch v-model="table.query.sorted" :active-value="1" :inactive-value="0" @change="tableFn.onSubmit"></el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="tableFn.onSubmit">搜索</el-button>
          <el-button type="primary" @click="tableFn.onResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="panel-table">
      <div class="table-head">
        <span>活动列表</span>
        <div>
          <el-button type="primary" @click="tableFn.gotoAdd" style="margin-right:20px">添加</el-button>
        </div>
      </div>
      <el-table
        :data="table.list"
        stripe
        :header-cell-style="{ backgroundColor: '#ededed'}"
        style="width: 100%"
        border>
        <el-table-column prop="id" label="活动ID" width="80px" />
        <el-table-column prop="eventsName" label="活动名称" />
        <el-table-column width="100px" prop="eventsStatus" label="活动状态">
          <template #default="{ row }">
            <el-tag :type="row.eventsStatus === 1 ? 'success' : row.eventsStatus === -1 ? 'info' : 'danger'">
              {{ tableFn.getItemFromArray(table.statusList, row.eventsStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="signUpStart" label="报名时间" />
        <el-table-column prop="eventsStartTime" label="活动开始时间" />
        <el-table-column width="100px" label="进行状态" prop="statusName">
          <template #default="{ row }">
            <el-link :type="['warning', 'success', 'primary', 'info', 'info'][row.timeStatus]" :underline="false">{{ row.statusName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column width="140px" prop="sortValue" label="排序值">
          <template #default="{ row }">
            <div class="weqwewq">
              <el-input-number
                v-model="row.sortValue"
                controls-position="right"
                :min="0"
                style="width: 100px"
                :max="9999"
                @change="(sortValue) => tableFn.changeSortValue(sortValue, row.id)"
              ></el-input-number>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="220px">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              plain
              @click="tableFn.gotoDetail(row)">详情</el-button>
            <el-button
              size="small"
              type="success"
              plain
              @click="tableFn.gotoEdit(row)">编辑</el-button> 
            <el-popover placement="bottom-start" trigger="click" :width="80" popper-class="self-popper">
              <template #reference>
                <el-button
                  size="small"
                  type="primary"
                  plain>更多</el-button>
              </template>
              <div>
                <el-button
                  size="small"
                  type="primary"
                  plain v-clipboard:copy="'/events/eventsDetail?id=' + row.id" v-clipboard:error="tableFn.clipboardError" v-clipboard:success="tableFn.clipboardSuccess" v-if="!table.isMerchant">复制链接</el-button>
                <el-button
                  type="danger"
                  size="small"
                  style="margin-left:0;margin-top:10px"
                  plain
                  @click="delFn.sureDelete(row)" v-if="row.eventsStatus !== 1">
                  删&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;除
                </el-button>
              </div>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination">
        <pagination
          :total="table.total"
          v-model:page="table.query.page"
          v-model:limit="table.query.pageSize"
          @pagination="tableFn.getTableList"
        />
      </div>
    </div>
  </div>
</template>


<script>
import { reactive } from "vue"
import { getEventsInfoList, deleteEventsInfo, addEventsInfo, changeEventsInfoSort } from "@/api/eventsinfo.js"
import { ElMessage, ElMessageBox } from "element-plus"
import { useRouter } from "vue-router"
import { ArrowDown } from '@element-plus/icons-vue'
import { getItemFromArray } from "@/utils/tool"
import UploadExcel from "@/components/UploadExcel"
import { useStore } from "@/store";
const store = useStore();
export default {
  name: "EventsInfoManage",
  components: {
    UploadExcel,
    ArrowDown
  },
  setup() {
    // 默认数据备份，以便重置或恢复
  const { $data: table, $fn: tableFn } = tableModule();
	const { $data: delData, $fn: delFn } = deleteModule(tableFn);
    return {
      table,
      tableFn,
      delData,
      delFn,
    };
  },
};

function tableModule() {
  const router = useRouter();

  const backup = {
    query: {
      pageSize: 10,
      page: 1,
      eventsName: '',
      publisher: '',
      eventsStartTime: [],
      signUpEndTime: [],
      eventsStatus: '',
      selfSupport: '',
      sorted: '',
      timeStatus: ''
    },
  };

  const $data = reactive({
    query: {
      pageSize: 10,
      page: 1,
      eventsName: '',
      eventsId: '',
      publisher: '',
      eventsStartTime: [],
      signUpEndTime: [],
      eventsStatus: '',
      selfSupport: '',
      sorted: '',
      timeStatus: ''
    },
    total: 0,
    list: [],
    url: {
      show: false,
      post: {
        id: "",
        url: "",
      },
    },
    statusList: [
      { key: 0, name: "下架" },
      { key: 1, name: "上架" },
      { key: -1, name: "草稿" }
    ],
    activityList: [
      { key: 0, name: "报名未开始" },
      { key: 1, name: "火热报名中" },
      { key: 2, name: "活动进行中" },
      { key: 3, name: "报名已结束" },
      { key: 4, name: "活动已结束" }
    ],
    isMerchant: store.getters.userInfo?.role === '商户'
  });
  const $fn = {
    onSubmit() {
      $fn.getTableList();
    },
    onResetQuery() {
      $data.query = { ...backup.query };
      $fn.getTableList();
    },
    getTableList() {
      const data = {
        ...$data.query,
        eventsStartTime: $data.query.eventsStartTime[0] || '',
        eventsEndTime: $data.query.eventsStartTime[1] || '',
        signUpStartTime: $data.query.signUpEndTime[0] || '',
        signUpEndTime: $data.query.signUpEndTime[1] || '',
        sorted: $data.query.sorted || ''
      }
      getEventsInfoList(data).then((res) => {
        if (res.code === 0) {
          $data.list = res.data.items || [];
          $data.total = res.data.pagination.total_record;
        }
      });
    },
    gotoDetail(row) {
      router.push("/eventsInfo/detail/" + row.id + "?view=reviewList");
    },
    gotoAdd() {
      router.push("/eventsInfo/edit");
    },
    gotoEdit(row) {
      router.push("/eventsInfo/edit/" + row.id);
    },
    openUrlPanel(row) {
      $data.url.show = true;
      $data.url.post.id = row.id;
      $data.url.post.url = row.url || "";
    },
    closeUrlPanel() {
      $data.url.show = false;
      $data.url.post = {
        id: "",
        url: "",
      };
    },
    clipboardSuccess() {
      ElMessage.success("复制成功");
    },
    clipboardError() {
      ElMessage.error("复制失败");
    },
    getItemFromArray(itemList, item) {
      return getItemFromArray(itemList, item);
    },
    changeSortValue(sortValue, rowId) {
      changeEventsInfoSort({
        id: rowId,
        sortValue
      }).then(res => {
        if (res.code === 0) {
          ElMessage.success("操作成功")
        }
      })
    }
  };
  $fn.getTableList();
  return {
    $data,
    $fn,
  };
}

// 删除
function deleteModule(tableFn) {
  const $fn = {
    sureDelete(row) {
      ElMessageBox.confirm("是否确认删除该活动？", "确认删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          $fn.deleteItem(row);
        })
        .catch(() => {});
    },
    deleteItem(row) {
      // 发起删除
      console.log("发起删除");
      deleteEventsInfo(row.id).then((res) => {
        if (res.code === 0) {
          ElMessage.success("删除成功！");
          tableFn.getTableList();
        }
      });
    },
  };
  return {
    $fn,
  };
}
</script>
<style scoped lang="scss">
@import "@/styles/tablePage.scss";
// .the-list {
//   height: 100%;
// }
.el-form-item {
  margin-bottom: 8px;
}
</style>
<style>
.el-popover.el-popper.self-popper{
  min-width: 80px !important;
}
</style>
